package com.ala4.oxcafe.event;

import com.ala4.oxcafe.boot.event.UserLoginEvent;
import com.ala4.oxcafe.boot.utils.DetailsHelper;
import com.ala4.oxcafe.common.utils.JSONUtil;
import com.ala4.oxcafe.common.utils.SmsClientUtil;
import com.ala4.oxcafe.entity.UserInfo;
import com.ala4.oxcafe.repository.UserInfoRepository;
import com.aliyun.sms.SMSPutDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 系统事件处理服务
 *
 * @author PING
 * @date 2025/8/17 14:06
 */
@Slf4j
@Service
@AllArgsConstructor
public class SystemEventProcessingService {

    private final UserInfoRepository userInfoRepository;

    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMPLETION, fallbackExecution = true)
    public void userLoginSuccess(UserLoginEvent userLoginEvent) {
        log.info("UserLoginEvent: {}", JSONUtil.toJsonStr(userLoginEvent));
        log.info("用户信息:{}", JSONUtil.toJsonStr(DetailsHelper.getUserDetails()));
        UserInfo userInfo = userInfoRepository.getById(userLoginEvent.getUserId());
        userInfo.setLoginIp(userLoginEvent.getLoginIp());
        userInfo.setLoginDate(userLoginEvent.getLoginDate());
        // 更新
        userInfoRepository.updateById(userInfo);
    }


    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMPLETION, fallbackExecution = true)
    public void sendSmsEvent(SendSmsEvent sendSmsEvent) {
        log.info("SendSmsEvent: {}", JSONUtil.toJsonStr(sendSmsEvent));
        log.info("SendSmsEvent: 发送短信-{}", sendSmsEvent.getPhoneNumber());
        SMSPutDTO smsPutDTO = new SMSPutDTO();
        smsPutDTO.setPhoneNumbers(sendSmsEvent.getPhoneNumber());
        smsPutDTO.setSmsTemplateEnum(sendSmsEvent.getSMSTemplate());
        smsPutDTO.setTemplateParam(JSONUtil.toJsonStr(sendSmsEvent.getTemplateParam()));
        SmsClientUtil.sendSms(smsPutDTO);
    }

}
